package com.xb.cloud.common.sms;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
public class SmsSender {
	private static final Logger logger = LoggerFactory.getLogger(SmsSender.class);

	@Resource
	private HttpClientService httpClientService;

	public static final String GET_SEND_MSG_URL = "https://106.ihuyi.com/webservice/sms.php?method=Submit&account={account}&password={APIKEY}&mobile={mobile}&content={content}";

	public static final String POST_SEND_MSG_URL = "https://106.ihuyi.com/webservice/sms.php?method=Submit";

	public static final String VERIFYCODE_TEMPLATE = "您的验证码是：%s。请不要把验证码泄露给其他人。如非本人操作，可不用理会！";

	public static final String ORDERPAYED_TEMPLATE = "尊敬的商户，您好！订单号： %s 已支付，请尽快安排配送。";

	public static String SMS_ACCOUNT = "C40453497";

	public static String SMS_PASSWORD = "f7cb9894856a3d0581def6b5b3045146";

	@Value("${SMS_ACCOUNT}")
	public void setSmsAccount(String SMS_ACCOUNT) {
		SmsSender.SMS_ACCOUNT = SMS_ACCOUNT;
	}

	@Value("${SMS_PASSWORD}")
	public void setSmsPassword(String SMS_PASSWORD) {
		SmsSender.SMS_PASSWORD = SMS_PASSWORD;
	}

	public boolean sendMsg(String mobile, String mobile_code) {
		String content = String.format(VERIFYCODE_TEMPLATE, mobile_code);

		long time = Calendar.getInstance().getTimeInMillis();
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("account", SMS_ACCOUNT);
		param.put("password", SMS_PASSWORD);
		param.put("mobile", mobile);
		param.put("content", content);
		param.put("time", String.valueOf(time));

		try {
			HttpResult httpResult = httpClientService.doPost(POST_SEND_MSG_URL, param);
			if (httpResult.getCode() == 200) {
				String body = httpResult.getBody();
				if (!StringUtils.isEmpty(body)) {
					Document doc = DocumentHelper.parseText(body);
					Element root = doc.getRootElement();
					String resCode = root.elementText("code");
					if ("2".equals(resCode)) {
						return true;
					}
					logger.error("短信验证码发送失败：{}", root.elementText("msg"));
				}
			}
		} catch (Exception e) {
			logger.error("sendTextMsg", e);
		}

		return false;
	}

	public boolean sendTextMsgCommon(String mobile, String content, String template) {
		content = String.format(template, content);

		long time = Calendar.getInstance().getTimeInMillis();
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("account", SMS_ACCOUNT);
		param.put("password", SMS_PASSWORD);
		param.put("mobile", mobile);
		param.put("content", content);
		param.put("time", String.valueOf(time));

		try {
			HttpResult httpResult = httpClientService.doPost(POST_SEND_MSG_URL, param);
			if (httpResult.getCode() == 200) {
				String body = httpResult.getBody();
				if (!StringUtils.isEmpty(body)) {
					Document doc = DocumentHelper.parseText(body);
					Element root = doc.getRootElement();
					String resCode = root.elementText("code");
					if ("2".equals(resCode)) {
						return true;
					}
					logger.error("短信验证码发送失败：{}", root.elementText("msg"));
				}
			}
		} catch (Exception e) {
			logger.error("sendTextMsg", e);
		}

		return false;
	}
}
